package com.hr.ping

import com.hr.ping.service.PingService
import com.hr.ping.util.FileLockUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import spock.lang.Specification

@SpringBootTest(classes = PingApplication)
@ActiveProfiles("dev")
class PingServiceTest extends Specification {

    @Autowired
    PingService pingService

    @Autowired
    WebClient webClient

    @Autowired
    FileLockUtil fileLockUtil

    def "ping should send request to pong and log the result"() {
        given:
        def mockWebClient = Mock(WebClient)
        def mockResponse = Mock(Mono)
        mockWebClient.method(_).uri(_).accept(_).retrieve().bodyToMono(String).thenReturn(mockResponse)
        mockResponse.doOnSuccess(_).thenReturn(Mono.just("World"))
        pingService.webClient = mockWebClient

        when:
        pingService.ping().block()

        then:
        1 * mockWebClient.method(_).uri(_).accept(_).retrieve().bodyToMono(String)
    }

    def "ping should handle rate limit"() {
        given:
        def mockWebClient = Mock(WebClient)
        def mockResponse = Mock(Mono)
        mockWebClient.method(_).uri(_).accept(_).retrieve().bodyToMono(String).thenReturn(mockResponse)
        mockResponse.doOnError(_).thenReturn(Mono.error(new RuntimeException("Rate limited")))
        pingService.webClient = mockWebClient

        when:
        pingService.ping().block()

        then:
        1 * mockWebClient.method(_).uri(_).accept(_).retrieve().bodyToMono(String)
    }
}
